import pandas as pd
import numpy as np
import os
import logging
from .coordinate_transformer import CoordinateTransformer

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)  # 设置为DEBUG级别以捕获详细转换日志

class KMLExporter:
    @staticmethod
    def transform_coordinates(csv_path, src_epsg, dest_epsg):
        """转换CSV文件中的坐标并保存新文件"""
        try:
            df = pd.read_csv(csv_path)
            transformer = CoordinateTransformer()
            transformer.set_crs(src_epsg, dest_epsg)
            # 添加坐标转换调试日志
            logger.debug(f"转换前坐标示例: X={df['X'].iloc[0]}, Y={df['Y'].iloc[0]}")
            lon, lat = transformer.transform(df['X'].values, df['Y'].values)
            logger.debug(f"转换后坐标示例: Lon={lon[0]}, Lat={lat[0]}")
            
            # 检查并处理无效坐标
            valid_mask = np.isfinite(lon) & np.isfinite(lat)
            if not np.all(valid_mask):
                invalid_count = np.sum(~valid_mask)
                logger.warning(f"检测到{invalid_count}个无效坐标点，已自动过滤")
                lon = lon[valid_mask]
                lat = lat[valid_mask]
                df = df[valid_mask].copy()
                
                if len(df) == 0:
                    logger.error("所有坐标点均无效，无法生成转换文件")
                    return None
            
            df['Lon'] = lon
            df['Lat'] = lat
            
            # 生成新的文件名
            base, ext = os.path.splitext(csv_path)
            transformed_csv = f"{base}_transformed{ext}"
            df.to_csv(transformed_csv, index=False)
            return transformed_csv
        except Exception as e:
            logger.error(f"坐标转换失败: {str(e)}")
            return None

    @staticmethod
    def generate_kml(csv_path, output_path, use_transformed=False):
        """从CSV文件生成KML文件"""
        try:
            df = pd.read_csv(csv_path)
            
            # 检查并过滤无效坐标点
            if use_transformed:
                if 'Lon' not in df.columns or 'Lat' not in df.columns:
                    logger.error("转换后的CSV文件缺少Lon或Lat列")
                    return False
                valid_mask = np.isfinite(df['Lon']) & np.isfinite(df['Lat']) & np.isfinite(df['OffsetElevation'])
            else:
                valid_mask = np.isfinite(df['X']) & np.isfinite(df['Y']) & np.isfinite(df['OffsetElevation'])
            
            df = df[valid_mask].copy()
            if len(df) == 0:
                logger.error("所有坐标点均无效，无法生成KML文件")
                return False
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write('<?xml version="1.0" encoding="UTF-8"?>')
                f.write('<kml xmlns="http://www.opengis.net/kml/2.2">')
                f.write('  <Document>')
                f.write(f'    <name>航线路径</name>')
                f.write('    <Placemark>')
                f.write('      <LineString>')
                f.write('        <coordinates>')
                
                if use_transformed and 'Lon' in df.columns and 'Lat' in df.columns:
                    coords = [f"{row.Lon},{row.Lat},{row.OffsetElevation}" for _, row in df.iterrows()]
                else:
                    coords = [f"{row.X},{row.Y},{row.OffsetElevation}" for _, row in df.iterrows()]
                
                f.write('          ' + ' '.join(coords) + '')
                f.write('        </coordinates>')
                f.write('      </LineString>')
                f.write('    </Placemark>')
                f.write('  </Document>')
                f.write('</kml>')
            return True
        except Exception as e:
            logger.error(f"KML生成失败: {str(e)}")
            return False

    @staticmethod
    def process_route_files(output_dir, num_routes, transform_coords=False, src_epsg=0, dest_epsg=0):
        """处理所有航线文件的坐标转换和KML生成"""
        results = []
        for idx in range(1, num_routes + 1):
            csv_path = os.path.join(output_dir, f"line_{idx:03}.csv")
            if not os.path.exists(csv_path):
                logger.warning(f"CSV文件不存在: {csv_path}")
                results.append((idx, False, "CSV文件不存在"))
                continue
            
            transformed_csv = None
            if transform_coords:
                transformed_csv = KMLExporter.transform_coordinates(csv_path, src_epsg, dest_epsg)
                if not transformed_csv:
                    results.append((idx, False, "坐标转换失败"))
                    continue
            
            kml_path = os.path.join(output_dir, f"line_{idx:03}.kml")
            success = KMLExporter.generate_kml(
                transformed_csv if transform_coords else csv_path,
                kml_path,
                use_transformed=transform_coords
            )
            
            if success:
                results.append((idx, True, kml_path))
            else:
                results.append((idx, False, "KML生成失败"))
        return results